<?php

namespace App\Services;

use App\Models\Sys_User;
use App\Models\Sys_User_Mechanism;
use App\Traits\ResponseApi;
use Illuminate\Support\Facades\Hash;

class UserService
{
    public function getUserList($params)
    {
        return Sys_User::getFilter($params)
            ->Status()
            ->select(['id','realname'])
            ->take(10)
            ->get();
    }

    public function getList($params)
    {
        $result = Sys_User::getFilter($params)->Nodel()->paginate($params['page_size']);
        foreach ($result as $key => $value){
            $result[$key]['role_name'] = $value->hasOneRole->role_name;
            $result[$key]['is_super'] = $value->hasOneRole->is_super;
        }
        $result->data = $result->makeHidden(['hasOneRole']);
        $list['list'] = $result->items();
        $list['total'] = $result->total();
        return ['status' => true,'code' => 200,'data' => $list];
    }

    public function addUser($params)
    {
        $params['plainpassword'] = $params['password'];
        $params['password'] = Hash::make($params['password']);
        if(isset($params['id']) && !empty($params['id'])){
            $res = Sys_User::where('id',$params['id'])->update([
                'avatar' => $params['avatar'],
                'username' => $params['username'],
                'password' => $params['password'],
                'role_id' => $params['role_id']
            ]);
            return ['status' => true,'code' => 200,'data' => $res];
        }else{
            $res = Sys_User::create($params);
            Sys_User_Mechanism::create(['mec_id' => $params['mec_id'],'user_id' => $res->id]);
            return ['status' => true,'code' => 200,'data' => $res];
        }

    }

    public function delUser($params)
    {
        $str = strstr((string)$params['ids'],',');

        if($str){
            $ids = explode(',',$params['ids']);
            $res = Sys_User::whereIn('id',$ids)->update(['is_del' => 'Y']);
        }else{
            $res = Sys_User::where('id',$params['ids'])->update(['is_del' => 'Y']);
        }

        return ['status' => true,'code' => 200,'data' => $res];
    }
}
